package cn.wolfcode.ssm.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.wolfcode.ssm.domain.Exam;
import cn.wolfcode.ssm.mapper.ExamMapper;
import cn.wolfcode.ssm.qo.QueryObject;
import cn.wolfcode.ssm.service.IExamService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class ExamServiceImpl implements IExamService {

    @Autowired
    private ExamMapper examMapper;


    @Override
    public Exam save(Exam exam) {
//​	    根据数量在id范围内随机生成5个单选题id,多选题id，判断题id

        ArrayList<Long> singleList =  examMapper.selectIdByType(1);//单选
        Integer singleNum = exam.getSingleNum();
        Set<Long> singleSet = RandomUtil.randomEleSet(singleList, singleNum);

        ArrayList<Long> multiList =  examMapper.selectIdByType(2);//多选
        Integer multiNum = exam.getMultiNum();
        Set<Long> multiSet = RandomUtil.randomEleSet(multiList, multiNum);
        ArrayList<Long> judgeList =  examMapper.selectIdByType(3);//判断
        Integer judgeNum = exam.getJudgeNum();
        Set<Long> judgeSet = RandomUtil.randomEleSet(judgeList, judgeNum);

//        先生成试卷，将数据插入试卷表
        Exam newExam = new Exam();
        newExam.setTitle(exam.getTitle());
        newExam.setExamMinute(exam.getExamMinute());
        newExam.setTotalScore(exam.getTotalScore());
        examMapper.insert(newExam);
//        再数据插入中间表 插入参数（试卷id，问题id（ids数组），序号（从0开始）index，分数）
        examMapper.insertExamQuestion(singleSet,newExam.getId(),exam.getSingleScore());
        examMapper.insertExamQuestion(multiSet,newExam.getId(),exam.getMultiScore());
        examMapper.insertExamQuestion(judgeSet,newExam.getId(),exam.getJudgeScore());
        return newExam;

    }

    @Override
    public void delete(Long id) {
        examMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Exam exam) {
        examMapper.updateByPrimaryKey(exam);
    }

    @Override
    public Exam get(Long id) {
        return examMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Exam> listAll() {
        return examMapper.selectAll();
    }

    @Override
    public PageInfo<Exam> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize()); //对下一句sql进行自动分页
        List<Exam> exams = examMapper.selectForList(qo); //里面不需要自己写limit
        return new PageInfo<Exam>(exams);
    }

}
